package org.shiro.demo.disruptor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.InitializingBean;

import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

// 写成 spring 管理类型 
public class DisruptorUtils implements InitializingBean {

	private static ExecutorService executor;
	private static Disruptor<TradeTransaction> disruptor;
	// private static EventHandlerGroup<TradeTransaction> handlerGroup;

	// spring 注入
	private TradeTransactionInWXHandler handler;

	public TradeTransactionInWXHandler getHandler() {
		return handler;
	}

	public void setHandler(TradeTransactionInWXHandler handler) {
		this.handler = handler;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		executor = Executors.newFixedThreadPool(4);
		int bufferSize = 1024;
		disruptor = new Disruptor<TradeTransaction>(new EventFactory<TradeTransaction>() {
			@Override
			public TradeTransaction newInstance() {
				return new TradeTransaction();
			}
		}, bufferSize, executor, ProducerType.SINGLE, new BusySpinWaitStrategy());
		disruptor.handleEventsWith(new TradeTransactionVasConsumer(), handler);
		disruptor.start();// 启动
	}

	public void publish(TradeTransactionEventTranslator tradeTransloator) {

		long beginTime = System.currentTimeMillis();
		executor.submit(new TradeTransactionPublisher(tradeTransloator, disruptor));
		System.out.println("总耗时:" + (System.currentTimeMillis() - beginTime));

	}

	public static void main(String[] args) throws InterruptedException {
		// TradeTransactionEventTranslator t = new
		// TradeTransactionEventTranslator();
		// publish(t);

	}
}